import {
  reqGetCategory1List,
  reqGetCategory2List,
  reqGetCategory3List
} from '@/api/product/category'

const state = {
  category1List: [],
  category2List: [],
  category3List: [],
  category1Id: '',
  category2Id: '',
  category3Id: ''
}

const mutations = {
  // 一级分类
  GET_CATEGORY1_LIST: (state, category1List) => {
    state.category1List = category1List
  },
  // 二级分类
  GET_CATEGORY2_LIST: (state, { data, category1Id }) => {
    state.category2List = data
    // 选中一级分类时，更新vuex数据使下拉列表选中值更新
    state.category1Id = category1Id
    // 修改一级分类时，清空二级和三级分类选中值
    state.category2Id = ''
    state.category3Id = ''
    state.category3List = []
  },
  // 三级分类
  GET_CATEGORY3_LIST: (state, { data, category2Id }) => {
    state.category3List = data
    state.category2Id = category2Id
    // 修改二级分类时，清空三级分类选中值
    state.category3Id = ''
  },
  // 选中三级分类后更新数据
  SET_CATEGORY3_ID: (state, category3Id) => {
    state.category3Id = category3Id
  },
  // 切换管理卸载组件时清空vuex中数据
  CLEAR_VUEX:(state)=>{
    state.category1List = []
    state.category2List = []
    state.category3List = []
    state.category1Id = ''
    state.category2Id = ''
    state.category3Id = ''
   }
}

const actions = {
  // 请求一级分类
  async getCategory1List({ commit }) {
    const { data } = await reqGetCategory1List()
    commit('GET_CATEGORY1_LIST', data)
  },
  // 请求二级分类
  async getCategory2List({ commit }, category1Id) {
    const { data } = await reqGetCategory2List(category1Id)
    commit('GET_CATEGORY2_LIST', { data, category1Id })
  },
  // 请求三级分类
  async getCategory3List({ commit }, category2Id) {
    const { data } = await reqGetCategory3List(category2Id)
    commit('GET_CATEGORY3_LIST', { data, category2Id })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
